// 数据统计工具类

/**
 * 计算平均值
 * @param {number[]} numbers - 数字数组
 * @returns {number} 平均值
 */
export function calculateAverage(numbers) {
  if (!numbers || numbers.length === 0) return 0;
  
  const sum = numbers.reduce((acc, num) => acc + num, 0);
  return sum / numbers.length;
}

/**
 * 计算最大值
 * @param {number[]} numbers - 数字数组
 * @returns {number} 最大值
 */
export function calculateMax(numbers) {
  if (!numbers || numbers.length === 0) return 0;
  
  return Math.max(...numbers);
}

/**
 * 计算最小值
 * @param {number[]} numbers - 数字数组
 * @returns {number} 最小值
 */
export function calculateMin(numbers) {
  if (!numbers || numbers.length === 0) return 0;
  
  return Math.min(...numbers);
}

/**
 * 计算中位数
 * @param {number[]} numbers - 数字数组
 * @returns {number} 中位数
 */
export function calculateMedian(numbers) {
  if (!numbers || numbers.length === 0) return 0;
  
  const sorted = [...numbers].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  
  if (sorted.length % 2 === 0) {
    return (sorted[mid - 1] + sorted[mid]) / 2;
  } else {
    return sorted[mid];
  }
}

/**
 * 计算标准差
 * @param {number[]} numbers - 数字数组
 * @returns {number} 标准差
 */
export function calculateStandardDeviation(numbers) {
  if (!numbers || numbers.length === 0) return 0;
  
  const mean = calculateAverage(numbers);
  const squaredDifferences = numbers.map(num => Math.pow(num - mean, 2));
  const averageSquaredDifference = calculateAverage(squaredDifferences);
  
  return Math.sqrt(averageSquaredDifference);
}

/**
 * 生成学习进度报告
 * @param {Object} goal - 学习目标数据
 * @returns {Object} 进度报告
 */
export function generateProgressReport(goal) {
  const subjects = goal.subjects || [];
  
  // 计算总体进度
  const totalProgress = calculateAverage(subjects.map(s => s.progress));
  
  // 找出最佳和最差科目
  const bestSubject = subjects.reduce((best, subject) => 
    subject.progress > best.progress ? subject : best, { progress: -1 });
  
  const worstSubject = subjects.reduce((worst, subject) => 
    subject.progress < worst.progress ? subject : worst, { progress: 101 });
  
  // 计算目标完成情况
  const completedSubjects = subjects.filter(s => s.progress >= 100).length;
  const totalSubjects = subjects.length;
  
  return {
    totalProgress: Math.round(totalProgress),
    bestSubject: bestSubject.name,
    bestProgress: bestSubject.progress,
    worstSubject: worstSubject.name,
    worstProgress: worstSubject.progress,
    completedSubjects,
    totalSubjects,
    completionRate: totalSubjects > 0 ? Math.round((completedSubjects / totalSubjects) * 100) : 0
  };
}

/**
 * 生成积分统计报告
 * @param {Object[]} pointsHistory - 积分历史记录
 * @returns {Object} 积分统计报告
 */
export function generatePointsReport(pointsHistory) {
  if (!pointsHistory || pointsHistory.length === 0) {
    return {
      totalIncome: 0,
      totalExpense: 0,
      netChange: 0,
      averageDaily: 0,
      mostCommonReason: '无数据'
    };
  }
  
  // 计算总收入和总支出
  let totalIncome = 0;
  let totalExpense = 0;
  const reasonCount = {};
  
  pointsHistory.forEach(record => {
    if (record.points > 0) {
      totalIncome += record.points;
    } else {
      totalExpense += Math.abs(record.points);
    }
    
    // 统计积分变动原因
    const reason = record.title || '未知';
    reasonCount[reason] = (reasonCount[reason] || 0) + 1;
  });
  
  // 找出最常见的积分变动原因
  let mostCommonReason = '';
  let maxCount = 0;
  
  for (const [reason, count] of Object.entries(reasonCount)) {
    if (count > maxCount) {
      maxCount = count;
      mostCommonReason = reason;
    }
  }
  
  // 计算净变化和日均变化
  const netChange = totalIncome - totalExpense;
  const days = Math.ceil((Date.now() - new Date(pointsHistory[0].time).getTime()) / (1000 * 60 * 60 * 24)) || 1;
  const averageDaily = Math.round(netChange / days);
  
  return {
    totalIncome,
    totalExpense,
    netChange,
    averageDaily,
    mostCommonReason
  };
}

/**
 * 格式化统计数字
 * @param {number} num - 要格式化的数字
 * @returns {string} 格式化后的数字字符串
 */
export function formatNumber(num) {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K';
  } else {
    return num.toString();
  }
}

export default {
  calculateAverage,
  calculateMax,
  calculateMin,
  calculateMedian,
  calculateStandardDeviation,
  generateProgressReport,
  generatePointsReport,
  formatNumber
};